package com.lagou.es.controller;

import com.lagou.es.model.HitsResult;
import com.lagou.es.service.PositionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Controller
public class PositionController {

    @Autowired
    private PositionService service;

    @GetMapping("/search/{keyword}/{pageNo}/{pageSize}")
    @ResponseBody
    public HitsResult searchPosition(@PathVariable("keyword") String  keyword, @PathVariable("pageNo")int pageNo,
                                                   @PathVariable("pageSize")int  pageSize)throws  IOException{

        // 页面不小于1
        pageNo = Math.max(pageNo, 1);
        // 分页大小不小于1
        pageSize = Math.max(pageSize, 1);

        HitsResult hitsResult = service.searchPos("positionName", keyword, pageNo, pageSize);
        // 如果查询的总结果不足5个，并且当前页显示不足
        if (hitsResult.getTotal() < 5 && (pageNo - 1) * pageSize + hitsResult.getHits().size() < 5) {
            List<Map<String, Object>> hits = hitsResult.getHits();

            HitsResult extraResult = service.searchPos("positionAdvantage", "美女多、员工福利好", 1, 5);
            // 额外添加的查询结果
            int start = hitsResult.getTotal();
            int end = start + extraResult.getTotal();

            int j = 0;
            for (int i = hitsResult.getTotal(); i < 5 && (pageNo - 1) * pageSize + hitsResult.getHits().size() < 5 && j < extraResult.getTotal(); i++, j++) {
                hitsResult.getHits().add(extraResult.getHits().get(j));
                hitsResult.setTotal(hitsResult.getTotal() + 1);
            }

        }

        return  hitsResult;
    }

    @RequestMapping("/importAll")
    @ResponseBody
    public String importAll() {

        try {
            service.importAll();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "success";
    }
}
